package com.cjjs.jsf.controller;

import java.util.Map;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.cjjs.jsf.service.WxService;
import com.cjjs.jsf.util.AES;
import com.cjjs.jsf.util.AjaxReturnVO;


/**
 * 微信服务后台
 * @author gxy
 *	2018年5月15日
 *	paltformManager
 *
 */
@RestController
@RequestMapping(value="/wx-user")
public class WXUserMessageController {
	
	@Autowired
	private WxService wxService;
	
	/**
	 * 获取用户openId和unionId数据(如果没绑定微信开放平台，解密数据中不包含unionId),并取得用户关联的商家
	 * @param encryptedData 加密数据
	 * @param iv 加密算法的初始向量
	 * @param code 微信登录码	
	 * @return
	 */
	@GetMapping(value="/getUserMessage")
	public AjaxReturnVO getUserMessage(@RequestParam(name="encryptedData") String encryptedData,
			@RequestParam(name="iv") String iv,@RequestParam(name="code") String wxCode) {
		
		AjaxReturnVO vo = new AjaxReturnVO();
		
		Map<String,Object> wxSessionMap = wxService.getWxSession(wxCode);
		
		if(null == wxSessionMap){
			return vo.setFail(vo, "50010");
		}
		//获取异常
		if(wxSessionMap.containsKey("errcode")){
			return vo.setFail(vo, "50020");
		}
		String sessionId = (String)wxSessionMap.get("session_key");
		
		if (StringUtils.isBlank(sessionId)) {
			return vo.setFail(vo, "40008");
		}
		
		try {
			
			AES aes = new AES();
			byte[] resultByte = aes.decrypt(Base64.decodeBase64(encryptedData), Base64.decodeBase64(sessionId), Base64.decodeBase64(iv));
			if(null != resultByte && resultByte.length > 0){
				String userInfo = new String(resultByte, "UTF-8");
				vo.setOk(true);
				vo.setMsg("0");
				vo.setData(userInfo);
				return vo;
			}
		} catch (Exception e) {
			e.printStackTrace();
			vo.setFail(vo, e.getMessage());
		}
		
		
		return vo;
		
	}
	
	

}
